/**
 * 
 */
package profile.aspect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import profile.ServerInfo;
import profile.ServerInfoHolder;


/**
 * @author ductrung.tran
 *
 */
@Aspect
public abstract class ServerInfoGetterAspect {

	
	@Pointcut
	public abstract void eliotDataServiceHelperNarrowPoincut();
	
	@Around("eliotDataServiceHelperNarrowPoincut()")
	public Object eliotDataServiceHelperNarrowAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
		//System.out.println("invoke");
		Object result = joinPoint.proceed();
		ServerInfoHolder.setServerInfo(getServerInfo(result));
		
		return result;
		
	}

	private ServerInfo getServerInfo(Object result) {
		ServerInfo info = new ServerInfo();
		info.setVersion(getIDLVersion(result));
		info.setServer(getServer(result));
		info.setDatabase(getDatabase(result));
		
		return info;
	}

	private String getDatabase(Object result) {
		try {
			Method method = result.getClass().getMethod("getDefaultDatabase");
			return (String) method.invoke(result);
		} catch (Exception e) {
			System.err.println("Cannot get database info");
			e.printStackTrace();
			return "UNKNOWN";
		}
	}

	private String getServer(Object result) {
		try {
			Method method = result.getClass().getMethod("getName");
			return (String) method.invoke(result);
		} catch (Exception e) {
			System.err.println("Cannot get server name");
			e.printStackTrace();
			return "UNKNOWN";
		}
	}

	private String getIDLVersion(Object result) {
		try {
			Class<?> klass = Class.forName("jeliot.eds.EliotDataServiceOperations");
			Field field = klass.getField("IDL_VERSION");
			return (String) field.get(null);
		} catch (Exception e) {
			System.err.println("Cannot get IDL Version ");
			e.printStackTrace();
			return "UNKNOWN";
		}
	}
}
